package com.luckymore.ydd.app.funcs.login;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.base.asynctaks.CountDownTask;
import com.base.cache.ACacheUtil;
import com.base.control.MFragmentSupport;
import com.base.control.TaskWithExceptionHandler;
import com.base.control.TextParamCheck;
import com.base.model.Bean2Json;
import com.base.util.Helper;
import com.base.util.StringUtil;
import com.base.view.dialog.MessageHintDialog;
import com.base.view.holder.ActionBarCommons;
import com.luckymore.ydd.app.R;
import com.luckymore.ydd.app.cache.CacheUtil;
import com.luckymore.ydd.app.model.MAppUser;
import com.luckymore.ydd.app.model.MSystem;
import com.luckymore.ydd.app.net.ApiClientFactory;
import com.luckymore.ydd.app.util.ActionBarSubControl;
import com.luckymore.ydd.app.util.MErrors;
import com.luckymore.ydd.app.util.MobileKeySet;

/**
 * Created by yjh on 15-3-12.
 */
public class PhoneVerifyFragment extends MFragmentSupport {
    private EditText phoneEdit;
    private EditText verifyEdit;
    private Button verifyBtn;
    private Button nextBtn;

    private String actionBarTitle = "注册";
    private static String verifyHintSuffix = "秒后重发";

    private int intentType = 0; //0 注册 1 忘记密码

    public PhoneVerifyFragment() {
        super();
    }

    @Override
    protected void create(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_phone_verify);

        //根据参数设置actionbar
        Bundle data = getArguments();
        if(data != null) {
            if((intentType = data.getInt(MobileKeySet.REGISTER_START_METHOD, -1)) == 1) {
                actionBarTitle = "忘记密码";
            }
        }

        phoneEdit = findViewById(R.id.register_phone);
        verifyEdit = findViewById(R.id.verify_num);
        verifyBtn = findViewById(R.id.get_verify_num);
        nextBtn = findViewById(R.id.verify_next_step);

        verifyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TaskWithExceptionHandler() {
                    @Override
                    public void onCheck() throws Exception {
                        TextParamCheck
                                .check(phoneEdit.getText().toString(), MErrors.PHONE_EMPTY, MErrors.PHONE_FORMAT_ERROR, TextParamCheck.PHONE_NUMBER_CHECKER);

                        //获取验证码
                        ApiClientFactory.getVerify(getMactivity(), PhoneVerifyFragment.this, "getVerifySuccess", phoneEdit.getText().toString());
                    }
                }.work(getActivity());
            }
        });

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new TaskWithExceptionHandler() {
                    @Override
                    public void onCheck() throws Exception {
                        TextParamCheck
                                .check(phoneEdit.getText().toString(), MErrors.PHONE_EMPTY, MErrors.PHONE_FORMAT_ERROR, TextParamCheck.PHONE_NUMBER_CHECKER);
                        TextParamCheck
                                .check(verifyEdit.getText().toString(), MErrors.VERIFY_EMPTY, MErrors.VERIFY_FORMAT_ERROR, TextParamCheck.VERIFY_CHECKER);


                        ApiClientFactory.register(getMactivity(), PhoneVerifyFragment.this,
                                "sentVerify", phoneEdit.getText().toString(), verifyEdit.getText().toString());
                    }
                }.work(getActivity());
            }
        });

        if(intentType == 1) { //为修改密码界面，填充手机号
            MAppUser.MUser mUser = ACacheUtil.getData(getMactivity(), CacheUtil.USER_INFO_CACHE_KEY);
            if(mUser != null) {
                phoneEdit.setText(StringUtil.emptyIfBlank(mUser.getPhone()));
            }
        }

        //test
//        FragmentControl.replace(getActivity(), new AccountSetFragment(), R.id.register_fragment, true);
    }

    public void getVerifySuccess(Bean2Json data) {
        MSystem.MRet ret = (MSystem.MRet)data;
        if(ret != null) {
            if(ret.getCode() == 1) { //获取成功
                int startNum = 60;
                verifyBtn.setText(startNum + verifyHintSuffix);
                new CountDownTask(verifyBtn, "", verifyHintSuffix, "重新发送").execute(startNum);
            } else {
                Helper.toast(getActivity(), ret.getMsg());
            }

        }
    }

    public void sentVerify(Bean2Json data) {
        MAppUser.MUser mUser = (MAppUser.MUser)data;
        if(mUser != null) {
            //注册成功更新缓存
            CacheUtil.updateUserInfo(getMactivity(), mUser, "");
            Helper.toast(getActivity(), "验证成功");
            getMactivity().replaceFragment(new AccountSetFragment(), R.id.register_fragment, true, null);
        } else {

        }
    }

    @Override
    public void setActionBar(ActionBar actionBar, Context context) {
        super.setActionBar(actionBar, context);

        ActionBarCommons abc = ActionBarSubControl.setActionBarCommons(getMactivity());

        abc.getTitleTv().setText(actionBarTitle);

        abc.getLeftBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回登录界面
                getActivity().finish();
            }
        });

    }

    @Override
    public void onRequestError(Integer errcode, String errmsg) {
        super.onRequestError(errcode, errmsg);
        switch(errcode) {
            case 100036:
                new MessageHintDialog(getMactivity(), false, MErrors.VERIFY_ERROR.getMsg(), MErrors.VERIFY_ERROR_HINT.getMsg()).show();break;
            default: Helper.toast(getActivity(), errmsg);
        }
    }
}
